public class T {
}


  class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }



public class Solution {
    public ListNode detectCycle(ListNode head) {

        if(head==null||head.next==null){
            return null;
        }


        ListNode fast=head.next.next;
        ListNode slow=head.next;





        while (fast!=null&&fast.next!=null){

            if(slow==fast){
                slow=head;
                while (slow!=fast){

                    slow=slow.next;
                    fast=fast.next;
                }

                if(slow==fast) {

                    return slow;
                }

            }

            fast=fast.next.next;
            slow=slow.next;
        }



        return null;



    }
}